<template>
  <div>
    <!-- 订单列表页面 -->
    <div class="order-management" v-if="currentView === 'list'">
      <div class="header">
        <el-breadcrumb separator=">">
          <el-breadcrumb-item>交易管理</el-breadcrumb-item>
          <el-breadcrumb-item>订单列表</el-breadcrumb-item>
        </el-breadcrumb>
        <h1>订单列表</h1>
      </div>

      <div class="filter-container">
        <div class="filter-row">
          <el-input
            v-model="filters.searchKeyword"
            placeholder="输入订单号/课程/用户"
            class="search-input"
            clearable
          />
          <el-select v-model="filters.paymentMethod" placeholder="支付方式" clearable class="search-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="支付宝" value="支付宝"></el-option>
            <el-option label="微信支付" value="微信支付"></el-option>
            <el-option label="未支付" value="未支付"></el-option>
          </el-select>
        </div>
        <div class="filter-row" style="margin-top: 15px; display: flex; justify-content: space-between">
          <div class="amount-range" style="width: 48%; display: flex; align-items: center; gap: 8px">
            <span style="flex-shrink: 0">实付金额</span>
            <el-input v-model="filters.minAmount" placeholder="最低金额" style="flex: 1"></el-input>
            <span style="flex-shrink: 0">-</span>
            <el-input v-model="filters.maxAmount" placeholder="最高金额" style="flex: 1"></el-input>
          </div>
          <div class="date-range" style="width: 48%; display: flex; align-items: center; gap: 8px">
            <span style="flex-shrink: 0">下单日期</span>
            <el-date-picker
              v-model="filters.startDate"
              type="date"
              placeholder="开始日期"
              style="flex: 1"
              value-format="YYYY-MM-DD"
            />
            <span style="flex-shrink: 0">-</span>
            <el-date-picker
              v-model="filters.endDate"
              type="date"
              placeholder="结束日期"
              style="flex: 1"
              value-format="YYYY-MM-DD"
            />
          </div>
        </div>
      </div>

      <div class="status-tabs">
        <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
          <el-tab-pane label="全部" name="all"></el-tab-pane>
          <el-tab-pane label="待支付" name="待支付"></el-tab-pane>
          <el-tab-pane label="已支付" name="已支付"></el-tab-pane>
          <el-tab-pane label="退款中" name="退款中"></el-tab-pane>
          <el-tab-pane label="已关闭" name="已关闭"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="order-list">
        <el-table :data="filteredOrders" style="width: 100%" border>
          <el-table-column prop="order_id" label="订单编号" width="140"/>
          <el-table-column prop="courseName" label="课程信息" width="240"/>
          <el-table-column prop="price" label="价格" width="120">
            <template #default="{ row }">
              ¥{{ Number(row.price).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="user_name" label="买家" width="95"/>
          <el-table-column prop="status" label="订单状态" width="160">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="pay_method" label="支付方式" width="100"/>
          <el-table-column prop="order_time" label="下单时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.order_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template #default="{ row }">
              <el-button size="small" @click="viewOrderDetail(row)">订单详情</el-button>
              <el-button 
                v-if="row.status === '待支付'" 
                size="small" 
                @click="closeOrder(row)"
              >关闭订单</el-button>
              <el-button 
                v-if="row.status === '已支付'" 
                size="small" 
                @click="handleRefund(row)"
              >退款</el-button>
              <el-button size="small" @click="showNoteDialog(row)">备注</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="orders.length"
        />
      </div>
    </div>

          <!-- 订单备注对话框 -->
          <el-dialog v-model="noteDialogVisible" title="添加订单备注" width="400px">
            <div class="note-dialog-content">
              <div class="order-info">
                <div>订单编号: {{ currentOrder.order_id }}</div>
                <div class="course-price">¥{{ Number(currentOrder.price).toFixed(2) }}</div>
                <div class="user-info">
                  <span>{{ currentOrder.user_name }}</span>
                </div>
                <div class="order-status">{{ currentOrder.status }}</div>
                <div>{{ currentOrder.pay_method }}</div>
              </div>
              <el-input
                v-model="currentNote"
                type="textarea"
                :rows="3"
                placeholder="请输入备注内容"
                style="margin-top: 20px;"
              ></el-input>
            </div>
            <template #footer>
              <el-button @click="noteDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveNote">确定</el-button>
            </template>
          </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getorderList, updateorder } from './../http/order'
import { useRouter } from 'vue-router'
import type { Order } from './../type/order'

const router = useRouter()
const currentPage = ref(1)
const pageSize = ref(10)

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
}
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
}
const currentView = ref('list')

// 订单数据
const orders = ref<Order[]>([])
onMounted(() => {
  orderList()
})
function orderList() {
  getorderList().then((response) => {
    if (response.data && response.data.results) {
      orders.value = response.data.results.map(item => ({
        objectId: item.objectId,
        order_id: item.order_id,
        courseName: item.courseName || '',
        price: item.price ? String(item.price).trim() : '0',
        user_name: item.user_name || '',
        status: item.status ? String(item.status).trim() : '',
        pay_method: item.pay_method && item.pay_method.trim() ? item.pay_method.trim() : '未支付',
        notes: item.notes || '',
        order_time: item.order_time || item.createdAt || item.updatedAt || ''
      }))
    }
  }).catch((err) => {
    ElMessage.error('获取订单列表失败')
  })
}

// 当前操作的订单
const currentOrder = ref<Order>({
  objectId: '',
  order_id: '',
  user_name: '',
  courseName: '',
  price: '0',
  status: '',
  pay_method: '未支付',
  notes: '',
  order_time: ''
})
const currentNote = ref('')
const noteDialogVisible = ref(false)

// 筛选条件
const filters = ref({
  searchKeyword: '',
  paymentMethod: '',
  minAmount: '',
  maxAmount: '',
  startDate: '',
  endDate: ''
})

// 状态标签
const activeStatus = ref('all')

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  if (!datetime) return ''
  // 只显示到秒
  return datetime.replace('T', ' ').substring(0, 19)
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const map = {
    '待支付': 'warning',
    '已支付': 'success',
    '退款中': 'info',
    '已关闭': 'danger'
  }
  return map[status] || ''
}

// 过滤后的订单
  const filteredOrders = computed(() => {
    let result = orders.value

    // 按状态筛选
    if (activeStatus.value !== 'all') {
      result = result.filter(order => order.status === activeStatus.value)
    }

    // 按支付方式筛选
    if (filters.value.paymentMethod) {
      result = result.filter(order => order.pay_method === filters.value.paymentMethod)
    }

    // 按金额范围筛选
    const minAmount = Number(filters.value.minAmount)
    const maxAmount = Number(filters.value.maxAmount)
    if (!isNaN(minAmount) && filters.value.minAmount !== '') {
      result = result.filter(order => Number(order.price) >= minAmount)
    }
    if (!isNaN(maxAmount) && filters.value.maxAmount !== '') {
      result = result.filter(order => Number(order.price) <= maxAmount)
    }

    // 按下单日期筛选
    if (filters.value.startDate) {
      result = result.filter(order => {
        if (!order.order_time) return false
        return order.order_time.substring(0, 10) >= filters.value.startDate
      })
    }
    if (filters.value.endDate) {
      result = result.filter(order => {
        if (!order.order_time) return false
        return order.order_time.substring(0, 10) <= filters.value.endDate
      })
    }

    // 按关键字搜索
    if (filters.value.searchKeyword) {
      const keyword = filters.value.searchKeyword.toLowerCase()
      result = result.filter(order => 
        (order.order_id && order.order_id.toLowerCase().includes(keyword)) ||
        (order.courseName && order.courseName.toLowerCase().includes(keyword)) ||
        (order.user_name && order.user_name.toLowerCase().includes(keyword))
      )
    }

    return result
})

// 查看订单详情
const viewOrderDetail = (order: Order) => {
  router.push({ path: '/detail', query: { id: order.objectId } })
}
// 关闭订单
const closeOrder = (order: Order) => {
  ElMessageBox.confirm('确定要关闭此订单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    order.status = '已关闭'
    ElMessage.success('订单已关闭')
  }).catch(() => {})
}

// 处理退款
const handleRefund = (order: Order) => {
  ElMessageBox.prompt('请输入退款原因', '退款', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(({ value }) => {
    order.status = '退款中'
    order.notes = value
    ElMessage.success('退款申请已提交')
  }).catch(() => {})
}

// 显示备注对话框
const showNoteDialog = (order: Order) => {
  currentOrder.value = { ...order }
  currentNote.value = order.notes || ''
  noteDialogVisible.value = true
}

// 保存备注
const saveNote = async () => {
  try {
    if (!currentOrder.value.objectId) {
      throw new Error('订单ID不能为空')
    }

    // 调用API更新备注
    const response = await updateorder(
      0, // 默认id
      '', // 默认planId 
      '', // 默认name
      currentOrder.value.objectId,
      {
        notes: currentNote.value
      }
    )

    if (response.status !== 200) {
      throw new Error('保存备注失败')
    }

    // 更新本地订单数据
    currentOrder.value.notes = currentNote.value
    const idx = orders.value.findIndex(o => o.objectId === currentOrder.value.objectId)
    if (idx !== -1) {
      orders.value[idx].notes = currentNote.value
    }
    
    noteDialogVisible.value = false
    ElMessage.success('备注已保存')
    
  } catch (error) {
    console.error('保存备注失败:', error)
    ElMessage.error('保存备注失败: ' + (error.message || '未知错误'))
  }
}

// 状态标签切换
const handleStatusChange = () => {
  // 可以添加额外的处理逻辑
}
</script>

<style scoped>
.order-management, .order-detail {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  width: 100%;
}

.header {
  margin-bottom: 20px;
}

.header h1 {
  font-size: 20px;
  margin: 10px 0;
}

.el-table {
  width: 100%;
}

.filter-container {
  background-color: #f5f7fa;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 15px;
}

.amount-range {
  display: flex;
  align-items: center;
  gap: 5px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 5px;
}

.status-tabs {
  margin-bottom: 20px;
}
.status-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: bold;
}

.filter-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.filter-row {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  margin-bottom: 15px;
}

.search-input,
.search-select {
  flex: 1;
  min-width: 0;
}

.order-list {
  width: 100%;
}

.course-info {
  display: flex;
  flex-direction: column;
}

.course-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.course-price {
  color: #f56c6c;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.order-detail .order-content {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-top: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #666;
}

.order-detail .course-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.order-detail .course-name {
  font-size: 16px;
  font-weight: bold;
}

.order-detail .user-info {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.order-status {
  margin-bottom: 15px;
}

.order-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.footer {
  margin-top: 20px;
  text-align: center;
}

.note-dialog-content .order-info {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  margin-bottom: 15px;
}

.note-dialog-content .user-info {
  display: flex;
  gap: 10px;
  margin: 5px 0;
}

.note-dialog-content .order-status {
  color: #f56c6c;
  margin: 5px 0;
}

.el-breadcrumb {
  margin-bottom: 15px;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0;
}

.status-desc {
  color: #999;
}
</style>